<!--  -->
<template>
  <div>
    <el-container class="screening-box">
      <el-form :inline="true" class="form" ref="form" label-position="right" label-width="100px">
        <el-header class="screening-head">
          <div class="title">
            <i class="el-icon-search el-icon--left"></i>筛选查询
          </div>
          <div>
            <span class="toggle" v-show="showScreening" @click="showScreening=!showScreening">
              <i class="el-icon-arrow-up el-icon--left"></i>收起筛选
            </span>
            <span class="toggle" v-show="!showScreening" @click="showScreening=!showScreening">
              <i class="el-icon-arrow-down el-icon--left"></i>展开筛选
            </span>
            <el-button class="tlwok-btn" type="primary" @click="getList">查询</el-button>
            <el-button class="tlwok-btn" type="primary" plain @click="searchName = ''">重置</el-button>
          </div>
        </el-header>
        <el-main class="screening-body" v-show="showScreening">
          <el-form-item label="三级类目名称：" label-width="100" prop="userName">
            <el-input v-model.trim="searchName" placeholder="请输入类目名"></el-input>
          </el-form-item>
        </el-main>
      </el-form>
    </el-container>
    <div class="table-box">
      <div class="table-title">
        <span class="title">
          <template v-for="(item , index) in rolePath">
            <el-link type="primary" @click="routerToNext(index)">{{item.name}}</el-link>
            <span v-if="index != (rolePath.length - 1)">/</span>
          </template>
        </span>
        <div>
          <el-button class="filing-button" type="primary" icon="el-icon-plus" @click="showAddDialog(null)">添加项目</el-button>
        </div>
      </div>
      <div class="list">
        <el-table ref="multipleTable" :data="tableData" style="width: 100%" border :header-cell-style="tableHeaderColor" :cell-style="tableCellStyle">
          <el-table-column prop="name" label="类目名称" width="280"></el-table-column>
          <el-table-column prop="filesCount" label="资质证书文件">
            <template slot-scope="scope">
              <div style="display:flex;flex-wrap: wrap;max-height: 100px;overflow-y: auto">
                <div style="margin-bottom: 10px;margin-right: 8%;width: 25%;display: flex;align-items: center;" v-for="(item , index) in scope.row.pictureList" :key="index">
                  <div style="cursor:pointer;text-decoration: underline;overflow: hidden;flex:1;text-overflow: ellipsis;white-space: nowrap;word-wrap: normal;word-wrap: break-word;word-break: break-all;text-align: left;" @click="showImage(item)" :title="item.name">{{item.name}}</div>
                  <el-link style="font-size: 18px;margin: 0 5px;" type="primary" @click="downImage(item.name , item.path)" icon="el-icon-download"></el-link>
                  <el-link style="font-size: 18px;margin: 0 5px;" type="primary" @click="deleteImage(item)" icon="el-icon-delete"></el-link>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template slot-scope="scope">
              <el-link type="primary" @click="showAddDialog(scope.row)">编辑名称</el-link>

              <el-upload class="upload-demo" :action="`api/manage/qualification/addImage?cid=${scope.row.id}`" ref="uploadControl" :limit="1" :before-upload="uploadBeforeUpload" :on-error="uploadError" :on-success="uploadSuccess" accept=".jpg, .jpeg, .png, .gif, .bmp, .pdf">
                <el-link>上传文件</el-link>
              </el-upload>

              <el-link type="primary" @click="del(scope.row)" :disabled="scope.row.filesCount > 0">删除类目</el-link>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-handler" v-if="tableData.length > 0">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.startPage" :page-sizes="pageInfo.pageSizeArr" :page-size="pageInfo.size" layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total"></el-pagination>
        </div>
      </div>
    </div>

    <el-dialog :title="this.editId > 0 ? '编辑' : '添加类目'" :visible.sync="addDialogVisible" center>
      <el-form :validate-on-rule-change="false" :inline-message="true" ref="userInfoForm" class="user-info-form" label-width="150px">
        <el-form-item label="分类名称：" prop="name">
          <el-input v-model.trim="addName" placeholder="请输入类目名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="toAdd">保 存</el-button>
        <el-button type="primary" plain @click="addDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="picDialogVisible">
      <div slot="title">
        <span style="font-size: 16px">{{picTitle}}</span>
        <span style="padding-left: 20px;font-size: 14px;color: #606266">(点击可下载)</span>
      </div>
      <!--      <div>点击图片可下载</div>-->
      <div class="demo-image__lazy">
        <el-image v-if="imageItem" :src="imageItem.path" @click="downImage(imageItem.name , imageItem.path)" lazy></el-image>
      </div>
      <span slot="footer" class="dialog-footer">
        <!--      <el-button @click="dialogVisible = false">取 消</el-button>-->
        <el-button type="primary" @click="picDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import md5 from 'js-md5'

export default {
  name: 'Project_list',
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      fileExtend: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'pdf'],

      tableData: [],
      searchName: '',
      showScreening: true,
      addDialogVisible: false,
      addName: '',
      editId: 0,

      parentId: 0,
      rolePath: {},
      pageInfo: {
        total: 0,
        pageSizeArr: [10, 20, 30, 40],
        size: 10, //分页页面数量大小
        startPage: 1, //开始页码
      },

      picDialogVisible: false,
      picTitle: '',
      imageItem: null,
    }
  },
  mounted() {
    this.parentId = this.$route.query.parentId || 0
    this.searchName = this.$route.query.searchName || ''
    let obj = this.$route.query.rolePath || ''
    if ((!this.searchName && this.parentId <= 0) || obj.length <= 0) {
      this.$message.error('路由错误')
      this.$router.back()
    }
    try {
      this.rolePath = JSON.parse(obj)
      console.log('this.rolePath', this.rolePath)
    } catch (e) {
      this.$message.error('路由错误')
      this.$router.back()
    }
    this.getList()
  },
  //方法集合
  methods: {
    showImage(item) {
      this.picTitle = item.name
      this.imageItem = item
      this.picDialogVisible = true
    },
    downImage(imageName, imgUrl) {
      let imgName = imageName
      var flieArr = imgUrl.split('.')
      let suffix = flieArr[flieArr.length - 1]
      this.$confirm(`是否下载图片【${imgName}】？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let image = new Image()
        // 解决跨域 Canvas 污染问题
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function() {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL('image/' + suffix) //得到图片的base64编码数据
          let a = document.createElement('a') // 生成一个a元素
          let event = new MouseEvent('click') // 创建一个单击事件
          a.download = imgName || 'photo' // 设置图片名称
          a.href = url // 将生成的URL设置为a.href属性
          a.dispatchEvent(event) // 触发a的单击事件
        }
        image.src = imgUrl
      })
    },
    deleteImage(item) {
      this.$confirm(`确定删除【${item.name}】图片吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$axios
          .post(`/api/manage/qualification/delImage`, `imageId=${item.id}`)
          .then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              this.search()
            } else this.$message.error(res.desc)
          })
      })
    },
    uploadBeforeUpload(file) {
      try {
        let last = file.name.substring(file.name.length - 3, file.name.length)
        last = last.toLowerCase()
        if (this.fileExtend.indexOf(last) < 0) {
          this.$message.error('文件类型错误')
          return false
        }
        //文件大小
        let size = file.size
        size = size / 1024 / 1024
        if (size > 5) {
          this.$message.error('文件大小不允许超过20M')
          return false
        }
        return true
      } catch (e) {
        this.$message.error('选择文件错误')
        return false
      }
    },
    uploadSuccess(response, file, fileList) {
      console.log('response', response)
      if (response.success) {
        this.$refs.uploadControl.clearFiles()
        this.$message.success('上传成功')
        this.search()
      } else {
        if (response.code == '00001') {
          location.reload()
        } else {
          this.$message.error('上传失败:' + response.desc)
          this.$refs.uploadControl.clearFiles()
        }
      }
    },
    uploadError(response, file, fileList) {
      this.$message.error('上传失败！')
      this.$refs.uploadControl.clearFiles()
    },
    uploadExceed(files, fileList) {
      this.$message.error('只能上传一个文件！')
    },
    routerToNext(indexNext) {
      let arg = []
      arg = this.rolePath.slice(0, indexNext + 1)
      let obj = JSON.stringify(arg)
      if (arg[indexNext].path == 'Qualification_Category_list') {
        this.$router.push(`${arg[indexNext].path}`)
      } else {
        this.$router.push(`${arg[indexNext].path}&rolePath=${obj}`)
      }
    },
    del: function(item) {
      this.$confirm(`确定删除【${item.name}】分类吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$axios
          .post(`/api/manage/qualification/deleteCategory`, `id=${item.id}`)
          .then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              this.search()
            } else this.$message.error(res.desc)
          })
      })
    },
    search: function() {
      this.pageInfo = {
        total: 0,
        pageSizeArr: [10, 20, 30, 40],
        size: 10, //分页页面数量大小
        startPage: 1, //开始页码
      }
      this.getList()
    },
    toAdd() {
      if (this.editId == 0) {
        this.$axios
          .post(
            `/api/manage/qualification/addCategory`,
            `name=${this.addName}&parentId=${this.parentId}`
          )
          .then(res => {
            if (res.success) {
              this.$message.success('添加成功')
              this.addDialogVisible = false
              this.getList()
            } else this.$message.error(res.desc)
          })
      } else {
        this.$axios
          .post(
            `/api/manage/qualification/updateCategory`,
            `name=${this.addName}&id=${this.editId}`
          )
          .then(res => {
            if (res.success) {
              this.$message.success('修改成功')
              this.addDialogVisible = false
              this.getList()
            } else this.$message.error(res.desc)
          })
      }
    },
    showAddDialog(item) {
      if (item == null) {
        this.editId = 0
        this.addName = ''
      } else {
        this.editId = item.id
        this.addName = item.name
      }

      this.addDialogVisible = true
    },

    getList: function() {
      let _this = this
      this.$axios
        .post(
          `/api/manage/qualification/getListPage?size=${this.pageInfo.size}&startPage=${this.pageInfo.startPage}`,
          { name: this.searchName, parentId: this.parentId, level: 2 }
        )
        .then(res => {
          if (res.success) {
            _this.pageInfo.total = res.result.total
            _this.pageInfo.size = res.result.pageSize
            _this.tableData = res.result.list
            if (!_this.tableData || _this.tableData.length < 1) {
              _this.$message({
                message: '未搜索到相关数据',
                type: 'error',
                // onClose: function() {
                // _this.$router.push(`Qualification_Category_list`)
                // },
              })
              return
            }

            let parentIdArr = _this.tableData[0].parentIds.split(',')
            if (_this.parentId < 1) {
              // 最外层直接搜索三级类目
              if (_this.tableData.length > 0)
                _this.parentId = _this.tableData[0].parentId
              _this.rolePath.push(
                {
                  name: _this.tableData[0].parentOneName,
                  path:
                    'Qualification_Category_second_list?parentId=' +
                    parentIdArr[0],
                },
                {
                  name: _this.tableData[0].parentTwoName,
                  path:
                    'Qualification_Category_third_list?parentId=' +
                    parentIdArr[1],
                }
              )
            } else {
              // 正常跳转
              _this.rolePath[2].name = _this.tableData[0].parentTwoName
            }
          } else {
            _this.$message({
              message: res.desc,
              type: 'error',
              // onClose: function() {
              // _this.$router.push(`Qualification_Category_list`)
              // },
            })
            return
          }
        })
    },

    // 分页数量大小设置
    handleSizeChange(val) {
      this.pageInfo.size = val
      this.pageInfo.startPage = 1
      this.getList()
    },
    // 分页当前页设置
    handleCurrentChange(val) {
      this.pageInfo.startPage = val
      this.getList()
    },
    // 修改table header的背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      return 'background-color: #f5f5f5;color: #333;font-weight: bold;text-align:center'
    },
    // 修改table tr行的样式
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      return 'text-align:center'
    },
  },
}
</script>


<style lang="less" scoped>
.box-card {
  margin: 30px;
}
.title {
  font-weight: bold;
}

.grey {
  color: #bbb;
}

.red {
  color: red;
}

.screening-box {
  border: 1px solid #ddd;

  .form {
    width: 100%;
  }
}

.screening-head {
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toggle {
    cursor: pointer;
    margin-right: 50px;
  }
}

.screening-body {
  border-top: 1px solid #ddd;
}

.btn-box {
  margin-top: 40px;

  .number {
    color: red;
  }

  .el-button--primary {
    .number {
      color: #fff;
    }
  }
}

.table-title {
  height: 47px;
  line-height: 47px;
  padding: 0 15px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .filing-button {
    margin-left: 30px;
  }
}

.table-box {
  border: 1px solid #ddd;
  margin-top: 30px;

  .el-tag {
    margin: 2px;
    cursor: default;
  }
}

.table-handler {
  padding: 5px 15px;
  text-align: right;

  .check-all {
    margin-right: 20px;
  }
}

.hasEdit {
  position: absolute;
  top: 0;
  left: 0;

  &::before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-top: 30px solid red;
    border-right: 30px solid transparent;
  }

  .text {
    position: absolute;
    top: -3px;
    left: 2px;
    color: #fff;
    font-size: 12px;
  }
}

.user-info-form {
  .el-select,
  .el-input {
    width: 300px;
  }

  .tags {
    width: 450px;
  }

  .el-tag {
    cursor: pointer;
    margin-right: 15px;
  }
}

.tags-dialog {
  .el-tag {
    margin-right: 15px;
    margin-bottom: 15px;

    &:last-child {
      margin-right: 30px;
    }
  }

  .button-new-tag {
    margin-bottom: 15px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
    color: #5aa3e5;
    border-color: #bddaf5;
    background: #eff6fc;

    &:focus,
    &:hover {
      color: #fff;
      background: #5aa3e5;
      border-color: #5aa3e5;
    }
  }

  .input-new-tag {
    width: 90px;
    margin-bottom: 15px;
    vertical-align: bottom;
  }
}

.upload-box {
  display: inline-block;
}
</style>
<style>
.list .el-card__body {
  padding: 0px !important;
}
.list .el-footer {
  padding: 0px;
}

.list .el-footer .el-button {
  margin: 0px;
}
</style>
